package com.arpa.oms.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.arpa.core.utils.collection.CollectionUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.cache.AreaCache;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.dto.WarehouseAuthorizationJsonBean;
import com.arpa.oms.domain.dto.OmsDefaultWarehouseDTO;
import com.arpa.oms.domain.entity.OmsDefaultWarehouse;
import com.arpa.oms.domain.vo.OmsCustomerVO;
import com.arpa.oms.domain.vo.OmsDefaultWarehouseVO;
import com.arpa.oms.mapper.OmsDefaultWarehouseMapper;
import com.arpa.oms.service.IOmsDefaultWarehouseService;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.entity.Location;
import com.arpa.wms.domain.entity.ReceiveItem;
import com.arpa.wms.domain.entity.Warehouse;
import com.arpa.wms.domain.entity.WarehouseSpace;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.ReceiveItemVO;
import com.arpa.wms.service.IInventoryService;
import com.arpa.wms.service.ILocationService;
import com.arpa.wms.service.IWarehouseSpaceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 默认发货仓库 服务实现类
 * </p>
 *
 * @author wangdong
 * @since 2021-07-27
 */
@Service
public class OmsDefaultWarehouseServiceImpl extends ServiceImpl<OmsDefaultWarehouseMapper, OmsDefaultWarehouse> implements IOmsDefaultWarehouseService {


    private IInventoryService iInventoryService;

    private final IWarehouseSpaceService iWarehouseSpaceService;

    private final ILocationService iLocationService;
    private final PartyCache partyCache;

    @Autowired
    private AreaCache areaCache;

    public OmsDefaultWarehouseServiceImpl(IInventoryService iInventoryService,
                                          IWarehouseSpaceService iWarehouseSpaceService,
                                          ILocationService iLocationService,
                                          PartyCache partyCache) {
        this.iInventoryService = iInventoryService;
        this.iWarehouseSpaceService = iWarehouseSpaceService;
        this.iLocationService = iLocationService;
        this.partyCache = partyCache;
    }

    /**
     * 查询合计,包含总数
     *
     * @param warehouseDTO
     * @return
     */
    @Override
    public OmsDefaultWarehouseVO queryListSum(OmsDefaultWarehouseDTO warehouseDTO) {

        OmsDefaultWarehouseVO warehouseVO = baseMapper.queryListSum(warehouseDTO);
        return warehouseVO;
    }

    /**
     * 查询列表
     *
     * @param warehouseDTO
     * @return
     */
    @Override
    public List<OmsDefaultWarehouseVO> queryList(OmsDefaultWarehouseDTO warehouseDTO) {

        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StringUtils.isNotEmpty(warehouseDTO.getSortField())) {
            warehouseDTO.setSortField(CommonUtil.camel2Underline(warehouseDTO.getSortField()));
        }
        return baseMapper.queryList(warehouseDTO);
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    @Override
    public boolean save(OmsDefaultWarehouseDTO entity) {
        //数据校验
        validateParameter(entity);
        OmsDefaultWarehouse warehouse = new OmsDefaultWarehouse();
        BeanUtil.copyProperties(entity, warehouse);
        warehouse.setCreatedBy(UserUtil.getCode());
        warehouse.setCreatedName(partyCache.translate(UserUtil.getCode()));
        warehouse.setGmtCreated(LocalDateTime.now());
        warehouse.setGroupCode(UserUtil.getBranchCode());
        warehouse.setCode(IdUtil.simpleUUID());
        if (CollectionUtil.isNotEmpty(entity.getProvinceCodes())) {
            String str = StringUtils.join(entity.getProvinceCodes().toArray(), ",");
            warehouse.setProvinceCode(str);
        }
        if (CollectionUtil.isNotEmpty(entity.getProvinceNames())) {
            String names = StringUtils.join(entity.getProvinceNames().toArray(), ",");
            warehouse.setProvinceName(names);
        }
        baseMapper.insert(warehouse);

        return true;
    }

    private void validateParameter(OmsDefaultWarehouseDTO entity) {
        String str = StringUtils.join(entity.getProvinceCodes().toArray(), ",");
        entity.setProvinceCode(str);
        //统一货主，店铺，省份下重量不能相交校验
        List<OmsDefaultWarehouse> omsDefaultWarehouses;
        if (StrUtil.isNotEmpty(entity.getCode())) {
            omsDefaultWarehouses = this.list(new LambdaQueryWrapper<OmsDefaultWarehouse>()
                    .eq(OmsDefaultWarehouse::getShipmentCode, entity.getShipmentCode())
                    .eq(OmsDefaultWarehouse::getShopCode, entity.getShopCode())
                    .eq(OmsDefaultWarehouse::getProvinceCode, entity.getProvinceCode()))
                    .stream().filter(info -> !info.getCode().equals(entity.getCode())).collect(Collectors.toList());
        } else {
            omsDefaultWarehouses = this.list(new LambdaQueryWrapper<OmsDefaultWarehouse>()
                    .eq(OmsDefaultWarehouse::getShipmentCode, entity.getShipmentCode())
                    .eq(OmsDefaultWarehouse::getShopCode, entity.getShopCode())
                    .eq(OmsDefaultWarehouse::getProvinceCode, entity.getProvinceCode()));
        }
        BigDecimal weightMinNew = entity.getWeightMin() != null ? entity.getWeightMin() : BigDecimal.ZERO;
        BigDecimal weihtMaxNew = entity.getWeightMax() != null ? entity.getWeightMax() : BigDecimal.ZERO;

        omsDefaultWarehouses.stream().forEach(info -> {
            BigDecimal weightMin = BigDecimal.ZERO;
            BigDecimal weihtMax = BigDecimal.ZERO;
            if (info.getWeightMin() != null) {
                weightMin = info.getWeightMin();
            }
            if (info.getWeightMax() != null) {
                weihtMax = info.getWeightMax();
            }
            if (weightMinNew.compareTo(weightMin) >= NumConst.NUM_ZERO && weightMinNew.compareTo(weihtMax) <= NumConst.NUM_ZERO) {
                throw new ServiceException("重量区间与已存在数据重合");
            }
            if (weihtMaxNew.compareTo(weightMin) >= NumConst.NUM_ZERO && weihtMaxNew.compareTo(weihtMax) <= NumConst.NUM_ZERO) {
                throw new ServiceException("重量区间与已存在数据重合");
            }
            if (weightMin.compareTo(weightMinNew) >= NumConst.NUM_ZERO && weightMin.compareTo(weihtMaxNew) <= NumConst.NUM_ZERO) {
                throw new ServiceException("重量区间与已存在数据重合");
            }
            if (weihtMax.compareTo(weightMinNew) >= NumConst.NUM_ZERO && weihtMax.compareTo(weihtMaxNew) <= NumConst.NUM_ZERO) {
                throw new ServiceException("重量区间与已存在数据重合");
            }
        });
    }

    @Override
    public Result closeLocationManagement(OmsDefaultWarehouse entity) {
        // 查询数据库，如果是刚改为关闭，则继续
        OmsDefaultWarehouse dbEntity = this.getOne(new QueryWrapper<OmsDefaultWarehouse>().lambda().eq(OmsDefaultWarehouse::getCode, entity.getCode()));
        if (NumConst.NUM_ZERO.equals(dbEntity.getLocationManagement())) {
            // 如果数据库中原本就是“关闭”状态，则视为已关闭，不用再继续之后的操作
            return Result.ok();
        }
        // 查询该仓库下是否有库存
        if (iInventoryService.warehouseHasInv(entity.getCode())) {
            throw new ServiceException("该仓库下有库存，无法关闭“启用库位管理”");
        }

        // 关闭该仓库下的库区、库位
        iWarehouseSpaceService.update(new UpdateWrapper<WarehouseSpace>().lambda().eq(WarehouseSpace::getWarehouseCode, entity.getCode())
                .eq(WarehouseSpace::getTempSpace, 0)
                .set(WarehouseSpace::getStatus, StatusEnum.UNACTIVE.getValue()));
        iLocationService.update(new UpdateWrapper<Location>().lambda().eq(Location::getWarehouseCode, entity.getCode())
                .eq(Location::getTempLocation, 0)
                .set(Location::getStatus, StatusEnum.UNACTIVE.getValue()));

        return Result.ok();
    }


    /**
     * 根据code更新
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateByCode(OmsDefaultWarehouse entity) {
        OmsDefaultWarehouseDTO dto = new OmsDefaultWarehouseDTO();
        BeanUtil.copyProperties(entity,dto);
        validateParameter(dto);
        entity.setModifiedBy(UserUtil.getCode());
        entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        if (entity.getProvinceCodes()!=null && entity.getProvinceCodes().size()>0){
            String str = StringUtils.join(entity.getProvinceCodes().toArray(), ",");
            entity.setProvinceCode(str);
        }else {
            entity.setProvinceCode("");
        }
        if (entity.getProvinceNames()!=null && entity.getProvinceNames().size()>0){
            String names = StringUtils.join(entity.getProvinceNames().toArray(), ",");
            entity.setProvinceName(names);
        }else {
            entity.setProvinceName("");
        }
        return baseMapper.update(entity, new QueryWrapper<OmsDefaultWarehouse>().lambda().eq(OmsDefaultWarehouse::getCode, entity.getCode()));
    }

    /**
     * 根据code更新启用、停用状态
     *
     * @param codes
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int activeStatus(List<String> codes) {
        int num = this.changeStatus(codes, StatusEnum.ACTIVE);
        return num;
    }

    /**
     * 根据code更新启用、停用状态
     *
     * @param codes
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> unactiveStatus(List<String> codes) {
        Map<String, Object> result = new HashMap<>();
        int num = 0;
        if (IterUtil.isNotEmpty(codes)) {
            num = this.changeStatus(codes, StatusEnum.UNACTIVE);
        }
        result.put(PropertyConst.SUCCESS, num);
        return result;
    }

    @Override
    public OmsDefaultWarehouseVO getOneByCode(String code) {
        OmsDefaultWarehouse warehouse = getOne(new QueryWrapper<OmsDefaultWarehouse>().lambda().eq(OmsDefaultWarehouse::getCode, code));
        if(warehouse==null){
            throw new ServiceException("仓库："+code+"不存在！");
        }
        List<String> result = Arrays.asList(warehouse.getProvinceCode().split(","));
        OmsDefaultWarehouseVO warehouseVO = new OmsDefaultWarehouseVO();
        BeanUtil.copyProperties(warehouse, warehouseVO);
        warehouseVO.setProvinceCodes(result);
        return warehouseVO;
    }


    /**
     * 变更仓库状态
     *
     * @param codes  标识
     * @param active 状态
     * @return
     */
    private int changeStatus(List<String> codes, StatusEnum active) {
        OmsDefaultWarehouse defaultWarehouse = new OmsDefaultWarehouse();
        defaultWarehouse.setStatus(Integer.valueOf(active.getValue()));
        return this.baseMapper.update(defaultWarehouse, new LambdaUpdateWrapper<OmsDefaultWarehouse>().in(OmsDefaultWarehouse::getCode, codes));
    }


}
